<template>
    <div>
      <vab-card>
        <template #header>
          <span class="leve_title">信用档案</span>
        </template>
        <template #default>
          <el-form
            :ref="(el: any) => (searchFormRef = el)"
            :model="searchForm"
            label-width="130px"
            class="form_search composite_form"
          >
            <el-row :gutter="24">
              <el-col
                v-for="(item, i) in DraftSearch"
                :key="i"
                :xs="24"
                :sm="12"
                :md="12"
                :lg="8"
                :xl="8"
              >
                <el-form-item
                  v-if="item.type == 'lazySelect'"
                  :label="item.label"
                  :prop="item.prop"
                >
                  <CreditLazySelect
                    v-model.trim="searchForm[item.prop]"
                    :type="item.lazyType"
                    @keyup.enter.native="onkeydown"
                  />
                </el-form-item>
                <el-form-item
                  v-if="item.type == 'select'"
                  :label="item.label"
                  :prop="item.prop"
                >
                  <VabSelectForm
                    :options="selectOptions(item.prop)"
                    v-model.trim="searchForm[item.prop]"
                    @keyup.enter.native="onkeydown"
                  />
                </el-form-item>
              </el-col>
              <!-- 按钮 -->
              <el-col :xs="24" :sm="24" :md="12" :lg="8" :xl="8">
                <div class="flex_just_end">
                  <el-button size="small" type="primary" @click="handleSearch()">
                    查询
                  </el-button>
                  <el-button size="small" @click="resetForm(searchFormRef)">
                    重置
                  </el-button>
                </div>
              </el-col>
            </el-row>
          </el-form>
        </template>
      </vab-card>
      <!-- 主 -->
      <vab-card shadow="always">
        <template #header>
          <div class="flex_sb">
            <span class="leve2_title">信用档案明细</span>
            <div class="flex_just_end">
              <el-button size="small" class="button_update" @click="handleClick('withdraw')">
                撤回审核
              </el-button>
              <el-button size="small" class="button_update" type="primary" @click="handleClick('create')">
                新建
              </el-button>
            </div>
          </div>
        </template>
        <el-table
          border
          height="460"
          style="width: 100%"
          :data="data.dataSource"
          v-loading="data.loading"
        >
          <el-table-column label="序号" align="center" width="60" fixed="left">
            <template #default="scope">
              <label
                class="el-checkbox"
                :class="{ 'is-checked': radioKey == scope.row.id }"
                @click="handleCurrentChange(scope.row)"
              >
                <span
                  class="el-checkbox__input"
                  :class="{ 'is-checked': radioKey == scope.row.id }"
                >
                  <span class="el-checkbox__inner"></span>
                </span>
                <span style="margin-left: 4px;">{{ (data.pageNum - 1) * data.pageSize + (scope.$index + 1) }}</span>
              </label>
            </template>
          </el-table-column>
          <el-table-column
            v-for="(item, i) in data.cloums"
            :key="i"
            :width="item.width"
            :prop="item.prop"
            :label="item.label"
            :align="item.type == 'money' || item.type == 'number' ? 'right' : 'center'
              "
          >
            <template #default="scope">
              <!-- 自定义 -->
              <div v-if="item.type == 'custom'">
                <span
                  v-if="item.prop == 'bill_no'"
                  class="ellipsis link"
                  @click="handleOperate('toDetail', scope.row.id)"
                >
                  {{ scope.row[item.prop] || '--' }}
                </span>
                <span
                  v-if="item.prop == 'status'"
                >
                  <el-tag  class="ml-2" :type="StatusColor(scope.row.status, true)">{{ StatusColor(scope.row.status) || '--' }}</el-tag>
                </span>
              </div>
              <!-- 正常 -->
              <div v-else class="ellipsis">
                {{ _FieldFormat(scope.row[item.prop], item.type) }}
              </div>
            </template>
          </el-table-column>
          <!-- 操作 -->
          <el-table-column label="操作" align="center" width="100" fixed="right">
            <template #default="scope">
              <el-button v-if="scope.row.status == 0 || scope.row.status == 3" size="small" type="primary" @click="handleOperate('toHandle', scope.row.id, scope.row)">去处理</el-button>
              <el-button v-else size="small" type="primary" @click="handleOperate('toDetail', scope.row.id)"
              >查看详情</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="flex_just_end">
          <el-pagination
            background
            small="small"
            v-model:current-page="data.pageNum"
            v-model:page-size="data.pageSize"
            layout="total, prev, pager, next,sizes, jumper"
            :page-sizes="[20, 50, 100, 200]"
            :pager-count="10"
            :total="data.count"
            @current-change="handlePageNum"
            @size-change="handlePageSize"
          />
        </div>
      </vab-card>
    </div>
  </template>
  <!-- 草稿箱 -->
<script lang="ts" setup>
defineOptions({
  name: 'CreditDraft',
})
/**
 * @import
 */
import {
  DraftSearch,
  DraftCloums,
  StatusColor,
  ReturnSelectOptions,
} from './component/tools'
import { DateFormat, FieldFormat } from '~/src/utils/utils'
import { ElMessage, ElMessageBox, FormInstance } from 'element-plus'
import { customerPriceStop } from '~/src/api/dms/customer';
import { organization_list } from '~/src/api/dms/organization';
import { crediRevokeExamine, creditDraftList } from '~/src/api/dms/credit';
import CreditLazySelect from './component/CreditLazySelect.vue'

/**
 * @var
 */
const proxy: any = getCurrentInstance()?.proxy

const router = useRouter()
const searchFormRef = ref<any>(null)
const searchForm = reactive<any>({})
const data = reactive<any>({
  dataSource: [],
  cloums: [],
  pageNum: 1,
  pageSize: 20,
  count: 0,
  search: {},
})

data.dataSource = []
data.cloums = DraftCloums

let isCheck = ref(false)
// 订单占有弹窗
const currentRow = ref<any>(null) //选中块
const radioKey = ref<any>(-1) //唯一值

/**
 * @method
 */
const handleSearch = async (value = '') => {
  isCheck.value = true
  await _GetProductList()
  ElMessage({
    message: '查询成功',
    type: 'success',
  })
}
// 重置
const resetForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  isCheck.value = false
  radioKey.value = -1
  currentRow.value = null

  data.pageNum = 1
  data.pageSize = 20
  await formEl.resetFields()
  await _GetProductList()
  ElMessage({
    message: '重置成功',
    type: 'success',
  })
}
// 回车
const onkeydown = (value: any) => {
  isCheck.value = true
  _GetProductList()
}

// 单选
const handleCurrentChange = (row: any) => {
  if (row.id == radioKey.value) {
    radioKey.value = -1
    currentRow.value = null
    return
  }
  radioKey.value = row.id
  currentRow.value = row
}
// 页码
const handlePageNum = (value: any) => {
  data.pageNum = value
  _GetProductList()
}
// 页数
const handlePageSize = (value: any) => {
  data.pageSize = value
  _GetProductList()
}

// 点击事件
const handleClick = (value: any) => {

  if (value == 'create') {
    router.push({
      path: '/credit/create',
      query: {
        from: 'create'
      }
    })
    return
  }
  if (!currentRow.value) {
    ElMessage({ type: 'warning', message: '请选择需要操作的草稿！' })
    return
  }

  const { id, status } = currentRow.value



  // 撤回
  if (value == 'withdraw') {
    if (status != 1) {
      proxy.$Message('该草稿无审核中的内容!', 'warning')
      return
    }
    crediRevokeExamine({ id }).then((res: any) => {
      proxy.$Message('撤回审核成功!', 'success')
      currentRow.value = null
      radioKey.value = -1
      _GetProductList()
    }).catch((err: any) => {

    })
    return
  }
  // 复制 新建
  if (value == 'update' && currentRow.value.status == 1) {
    proxy.$Message('该草稿正在审核中，无法进行更新操作！', 'warning')
    return
  }

  // 草稿状态
  if (value == 'update' && status == 0) {

    ElMessageBox({
      title: '提示',
      message: h('p', null, [
        h('span', undefined, '该订单尚未提交，可直接点击'),
        h('span', {
          style: 'cursor: pointer;font-weight: 600',
          onClick: () => {
            handleOperate('toHandle', currentRow.value.id)
            //关闭弹窗
            ElMessageBox.close()
          }

        }, '【去处理】',),
        h('span', undefined, '按钮进行编辑'),
      ]),

      confirmButtonText: '确定',
      cancelButtonText: '取消',
    })
    return
  }

  if (value == 'copy' || value == 'update') {
    router.push({
      path: '/customer/priceListCreate',
      query: {
        id: currentRow.value.id,
        from: value
      }
    })
  }
}
// 操作事件
const handleOperate = (value: string, id: string | number, row = {}) => {
  if (value == 'toHandle') {
    router.push({ path: '/credit/create', query: { id, from: 'toHandle', handleStatus: row.status } })
  }
  if (value == 'toDetail') {
    router.push({ path: '/credit/detail', query: { id } })
  }
}
// 字段级格式化
const _FieldFormat = (value: string, type = '') => {
  if (type == 'time') return DateFormat(value, 'YYYY-MM-DD')
  return FieldFormat(value, type)
}
// 筛选项
const _GetProductSearch = async () => {
  try {
    const orgRes = await organization_list({})
    data.search.org_list = await orgRes.data
  } catch (error) { }
}
// 筛选项返回值
const selectOptions = (value: string) => {
  if (!data.search) return
  if (!value) return
  return ReturnSelectOptions(data.search, value)
}
// 获取数据
const _GetProductList = async () => {
  data.loading = true

  let _searchForm = { ...searchForm }

  if (!isCheck.value) _searchForm = {}

  const query = {
    page: data.pageNum,
    limit: data.pageSize,
    filter: {
      customer_number: _searchForm.customer_number || '', // 信用对象
      bill_no: _searchForm.bill_no || '', // 信用编号
    },
  }

  try {
    const res = await creditDraftList({ ...query })
    data.dataSource = res.data.list
    data.count = res.data.count
    data.loading = false
  } catch (error) { }
}
onActivated(() => {
  _GetProductList()
  _GetProductSearch()
  currentRow.value = null
  radioKey.value = -1
})
</script>
  
<style lang="scss" scoped>
@import '../../components/public.scss';
</style>
  ./component/priceOutside/tools
  